package com.movie.ticket.sale.authorassembly.controller;

import com.alibaba.fastjson.JSON;
import com.movie.ticket.sale.authorassembly.AOCR.IDJsonBean;
import com.movie.ticket.sale.authorassembly.AOCR.Idcard;
import com.movie.ticket.sale.authorassembly.component.PrintCodeUtil;
import com.movie.ticket.sale.authorassembly.component.UpdateUtil;
import com.movie.ticket.sale.authorassembly.dao.TCinemaContractMapper;
import com.movie.ticket.sale.authorassembly.dao.TCinemaDataMapper;
import com.movie.ticket.sale.authorassembly.dao.TCinemaMapper;
import com.movie.ticket.sale.authorassembly.dao.TManagerMapper;
import com.movie.ticket.sale.authorassembly.dao.TUserMapper;
import com.movie.ticket.sale.call.MovieTicket;
import com.movie.ticket.sale.moviecommon.common.Result;
import com.movie.ticket.sale.moviecommon.model.TCinema;
import com.movie.ticket.sale.moviecommon.model.TCinemaContract;
import com.movie.ticket.sale.moviecommon.model.TCinemaData;
import com.movie.ticket.sale.moviecommon.model.TManager;
import com.movie.ticket.sale.moviecommon.model.TUser;
import com.movie.ticket.sale.provide.MovieAuthor;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author： Micsal
 * @create-time： 2020.12.08 18:47
 * @version： 1.0
 * @description： desc
 */
@RestController
@Slf4j
public class Author implements MovieAuthor {
    //配置注入
    @Value("${custom.telPattern}")
    private String telPattern;

    //注入mapper
    @Autowired
    private TUserMapper tuserMapper;
    @Autowired
    private TManagerMapper tmanagerMapper;
    @Autowired
    private TCinemaMapper tCinemaMapper;
    @Autowired
    private TCinemaDataMapper tCinemaDataMapper;
    @Autowired
    private TCinemaContractMapper tCinemaContractMapper;

    //注入其他的微服务
    @Autowired
    private MovieTicket movieTicket;

    //注入组件
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result getTelCode(String tel) {
        log.info("------ 获取手机验证码：{}", tel);

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        String key = tel + ".MessageAuthenticationCode";                      //短信验证码存redis-key：手机号_MessageAuthenticationCode
        BoundValueOperations<String, String> rs = redisTemplate.boundValueOps(key);

        String old = rs.get();
        if (null != old) {
            long time = Long.parseLong(old.split("-")[1]);
            if ((new Date().getTime() - time) < 100000)                     //这里100s是防止绕过前端，恶意请求
                return Result.fail(426, "please interval 100s to get the message code");//100s间隔 前端设置个定时，发送按钮变灰，100s倒计时
        }

        int code = (int) (Math.random() * 9000) + 1000;
        String value = code + "-" + new Date().getTime();
        Result ms = movieTicket.sendMessage(tel, code + "");
        if (ms.isSuccess()) {
            rs.set(value, 10, TimeUnit.MINUTES);                    //redis-key存活时间：10分钟
            return Result.success(value);
        } else
            return ms;
    }

    @Override
    public Result checkTelCode(String tel, String code) {
        log.info("------ 校验短信验证码：{}，{}", tel, code);
        return movieTicket.checkMessage(tel, code);
    }

    /**
     * 获取请求的ip
     */
    private String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    @Override
    public Result getRandomNum() {
        log.info("------ 获取图片验证码");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();

        //获取用户ip
        String ip = getIpAddr(request);
        log.info("请求来自：{}", ip);
        ip = ip.replaceAll("\\.", ""); //.在java中代表任意字符，用\\.表示

        String key = ip + ".RandomNumber";    //key
        BoundValueOperations<String, String> rs = redisTemplate.boundValueOps(key);
        String value = rs.get();
        if (null != value) {
            long time = Long.parseLong(value.split("-")[1]);
            if ((new Date().getTime() - time) < 1500) {
                response.setStatus(426);
                return Result.fail(426, "请求太快，请勿重复刷新");
            }
        }

        PrintCodeUtil num = new PrintCodeUtil();
        BufferedImage image = num.getImage();

        try {
            ImageIO.write(image, "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail(426, "网络不稳定，图片传输丢失");
        }
        //<img src="http://localhost:8351/author/getRandomNum" alt="http://localhost:8351/author/getRandomNum">
        String text = num.getText();
        value = text + "-" + new Date().getTime();
        rs.set(value, 3, TimeUnit.MINUTES);
        return Result.success();
    }

    @Override
    public Result checkRandomNum(String code) {
        log.info("------ 校验图片验证码");
        if (null == code || code.length() != 4)
            return Result.fail(426, "非法输入");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //获取用户ip
        String ip = getIpAddr(request);

        ip = ip.replaceAll("\\.", ""); //.在java中代表任意字符，用\\.表示

        String key = ip + ".RandomNumber";    //key
        BoundValueOperations<String, String> rs = redisTemplate.boundValueOps(key);
        String value = rs.get();
        if (null != value) {
            if (code.equalsIgnoreCase(value.split("-")[0]))
                return Result.success("校验成功");
            else
                return Result.fail(426, "验证码错误");
        } else
            return Result.fail(426, "验证码已失效");
    }

    @Override
    public Result registerCheckUseName(String userName) {
        log.info("------ 昵称实时校验：{}", userName);
        if (null == userName || userName.length() > 9 || userName.length() < 3) //长度3-9位
            return Result.fail(426, "昵称长度位3-9位");
        String[] sensitiveWordCha = {"政治", "伊斯兰"};
        String[] sensitiveWordEng = {"shit", "drug", "gun", "root"};
        if (Arrays.binarySearch(sensitiveWordCha, userName) != -1 && Arrays.binarySearch(sensitiveWordEng, userName) != -1)
            return Result.fail(426, "昵称包含敏感字符");
        if (tmanagerMapper.checkNameIsBeUsed(userName).size() != 0)
            return Result.fail(426, "该昵称已被使用");
        return Result.success("昵称可用");
    }

    @Override
    public Result registerCheckTel(String tel) {
        log.info("------ 手机号实时校验:{}", tel);
        if (tel == null || "".equals(tel))
            return Result.fail(426, "手机号不能为空");
        if (!tel.matches(telPattern))
            return Result.fail(426, "手机号不合法");
        if (tmanagerMapper.checkTelIsBeUsed(tel).size() != 0)
            return Result.fail(426, "该手机号已被使用");
        return Result.success("手机号未被注册");
    }

    @Override
    public Result userRegisterCheckMessage(String tel, String pass, String userName) {
        log.info("------ 用户注册:{},{},{}", tel, pass, userName);
        Result r1 = registerCheckTel(tel);
        if (!r1.isSuccess())
            return r1;
        Result r2 = registerCheckUseName(userName);
        if (!r2.isSuccess())
            return r2;
        if (!pass.matches("^[A-Za-z][a-zA-Z0-9]{5,11}$")) //字母开头，数组+字母6-12位
            return Result.fail(426, "密码不符合规则");
        TUser user = new TUser(0, 1, userName, pass, tel, 0, "", "", 0, "", "", 0, 1);
        TManager manager = new TManager(0, 1, pass, userName, tel);
        tuserMapper.addANewUser(user);
        tmanagerMapper.addANewManager(manager);
        if (loginNamePass(userName, pass).isSuccess())
            return Result.success("login success"); //注册并登录成功
        return Result.success("register success");  //单纯注册成功
    }

    @Override
    public Result loginNamePass(String name, String pass) {
        log.info("------ 账号密码登录:{},{}", name, pass);
        if (null == name || null == pass)
            return Result.fail(426, "用户名或密码不能为空");
        TManager manager = tmanagerMapper.findByName(name);
        if (null == manager)
            return Result.fail(426, "用户不存在");
        if (manager.getPassword().equals(pass)) {

            int id = tmanagerMapper.getIdFromRoleAndTel(manager.getRole(), manager.getTel());
            manager.setId(id);

            return Result.success(manager);
        } else
            return Result.fail(426, "密码错误");
    }

    @Override
    public Result loginGetCode(String tel) {
        log.info("------ 获取登录验证码:{}", tel);
        if (null == tel)
            return Result.fail(426, "电话或验证码不能为空");
        TManager manager = tmanagerMapper.findByTel(tel);
        if (null == manager)
            return Result.fail(426, "用户不存在");
        else
            return getTelCode(tel);
    }

    @Override
    public Result loginCheckCode(String tel, String code) {
        log.info("------ 校验登录验证码:{},{}", tel, code);
        if (null == tel || null == code)
            return Result.fail(426, "电话或验证码不能为空");
        Result re1 = checkTelCode(tel, code);
        if (re1.isSuccess()) {
            TManager manager = tmanagerMapper.findByTel(tel);

            int id = tmanagerMapper.getIdFromRoleAndTel(manager.getRole(), manager.getTel());
            manager.setId(id);

            return Result.success(manager);
        } else
            return re1;
    }

    @Override
    public Result loginWxGetQRCode() {
        return null;
    }

    @Override
    public Result loginWxCallBack(String code, String state) {
        return null;
    }

    @Override
    public Result logout() {
        log.info("------ 登出");
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //从request中获取id和role
        try {
            String id = request.getHeader("id");
            String role = request.getHeader("role");
            String key = "manager." + role + "." + id;
            log.info("获取key：{}", key);
            redisTemplate.delete(key);
            return Result.success();
        } catch (Exception e) {
            return Result.fail(426, e.getMessage());
        }
    }

    @Override
    public Result cinemaApplyGetCode(String tel) {
        log.info("------ 影院入驻，获取短信验证码：{}", tel);
        Result re1 = registerCheckTel(tel);
        if (!re1.isSuccess())
            return re1;
        return getTelCode(tel);
    }

    @Override
    public Result cinemaApplyCheckCode(String tel, String code) {
        log.info("------ 影院入驻，校验短信验证码:{},{}", tel, code);
        if (null == tel || null == code)
            return Result.fail(426, "电话或验证码不能为空");
        return checkTelCode(tel, code);
    }

    @Override
    public Result cinemaApplyCheckNameAndPass(String tel, String pass, String name) {
        log.info("------ 影院申请，注册:{},{},{}", tel, pass, name);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String ip = getIpAddr(request);
        ip = ip.replaceAll("\\.", "");

        //重复容错
        List<TManager> tManagers = tmanagerMapper.checkTelIsBeUsed(tel);
        log.info("容错的列表大小：{}", tManagers.size());
        if (tManagers.size() != 0 && tManagers.get(0).getRole() == 2) {
            log.info("容错的列表，角色信息：{}", tManagers.get(0).getRole());
            TCinema cinema1 = tCinemaMapper.getCinemaByTel(tel);
            if (redisTemplate.boundValueOps("CRU." + ip).get() != null)//重复请求
                return Result.success("注册信息还在，请进行下一步操作");
            else if (cinema1.getState() == -9) {      //倒回容错
                String key = "CRU." + ip;
                BoundValueOperations<String, String> rs = redisTemplate.boundValueOps(key);
                String value = cinema1.getId() + "-" + tel + "-" + new Date().getTime();
                rs.set(value, 24, TimeUnit.HOURS);
                return Result.success("重新载入redis信息");
            }
        }

        Result r1 = registerCheckTel(tel);
        if (!r1.isSuccess())
            return r1;
        Result r2 = registerCheckUseName(name);
        if (!r2.isSuccess())
            return r2;
        if (!pass.matches("^[A-Za-z][a-zA-Z0-9]{5,11}$")) //字母开头，数组+字母6-12位
            return Result.fail(426, "密码不符合规则");
        TCinema cinema = new TCinema();
//        System.out.println(cinema);
        cinema.setId(99);
        cinema.setRole(2);
        cinema.setPassword(pass);
        cinema.setTel(tel);
        cinema.setName(name);
        cinema.setCinemaName("default");
        cinema.setState(-9);        //-9申请1阶段，定时清除
        cinema.setDegree(0);
        cinema.setTipRoot(0.5);
        TManager manager = new TManager(0, 2, pass, name, tel);
//        System.out.println(cinema);

        String key = "CRU." + ip;
        BoundValueOperations<String, String> rs = redisTemplate.boundValueOps(key);

        tCinemaMapper.addNewCinema(cinema);
        log.info("获取自增id：{}", cinema.getId());
        String value = cinema.getId() + "-" + tel + "-" + new Date().getTime();
        rs.set(value, 24, TimeUnit.HOURS);
        tmanagerMapper.addANewManager(manager);
        return Result.success("register success");
    }

    @Override
    public Result getAllCinemaFather() {
        List<TCinema> cinemas = tCinemaMapper.findAllCinemaFather();
        if (cinemas.size() == 0)
            return Result.fail(426, "没有父级影院");
        Map<String, String> map = new HashMap<String, String>();
        for (TCinema c : cinemas)
            map.put(c.getId() + "", c.getCinemaName());
        return Result.success(map);
    }

    @Override
    public Result cinemaApplyUpdateLegalFile(MultipartFile[] files, String account, String cinemaName, String name, String identity, int degree, String registerNum, int chain) {

        if (null == files || null == account || null == cinemaName || null == name || null == identity || null == registerNum)
            return Result.fail(426, "信息不能为空");
        if (files.length < 4)
            return Result.fail(426, "文件数目不正确");
        if (!account.matches("^[1-9][0-9]{12,18}$"))
            return Result.fail(426, "银行账户错误");
//        if (!cinemaName.matches("^[a-zA-Z0-9]{2,12}$"))
        if (cinemaName.length() < 3)
            return Result.fail(426, "影院名称长度不符合要求(大于3)");
        if (name.length() < 1 || name.length() > 20)
            return Result.fail(426, "姓名不符合规范");
//        if (!identity.matches("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$"))
//            return Result.fail(426, "身份证不符合规范");
        if (registerNum.length() != 15)
            return Result.fail(426, "营业执照不正确");
        if (degree == 2 && chain <= 0)  //查询公司注册信息，确认关系
            return Result.fail(426, "未指向正确的父级院线");

        Result re0 = recognizeImg(files[0]);
        if (!re0.isSuccess())
            return re0;

        Map<String, String> map = (Map<String, String>) re0.getData();
        String reId = map.get("idNum");
        String reName = map.get("name");

        if (!reName.equals(name))
            return Result.fail(426, "名称与上传身份证不一致");

        if (!reId.equals(identity))
            return Result.fail(426, "身份证号与上传身份证不一致");

        int id = getCinemaIdfromRedis();
        if (id == 0)
            return Result.fail(426, "信息已失效，请重新操作");

        if (tCinemaMapper.selectById(id).getState() != -9)
            return Result.fail(426, "法人信息已上传，请勿重复操作");

        //第一个文件的流已经被读出，重新写入
        String path = map.get("path");
        File f1 = new File(path);
        try (InputStream inputStream = new FileInputStream(f1)) {
            MultipartFile multi = new MockMultipartFile(f1.getName(), f1.getName(), "", inputStream);
            files[0] = multi;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("重新读取inputStream转换为MultipartFile失败：{}", e.getMessage());
            return Result.fail(426, e.getMessage());
        } finally {
            //删除文件
            f1.delete();
        }

        Result re1 = new UpdateUtil().updateFiles("cinema", files, id);
        if (!re1.isSuccess())
            return re1;
        String[] urls = (String[]) re1.getData();

        TCinema cinema = new TCinema();
        cinema.setId(id);
        cinema.setAccount(account);
        cinema.setCinemaName(cinemaName);
        cinema.setLegalPerson(name);
        cinema.setLpIdNumber(identity);
        cinema.setDegree(degree);
        cinema.setRegisterNumber(registerNum);
        cinema.setChain(chain);
        cinema.setState(-8);

        TCinemaData cinemaData = new TCinemaData();
        cinemaData.setId(0);
        for (int i = 0; i < urls.length; i++) {
            cinemaData.setCinemaId(id);
            cinemaData.setFilePath(urls[i]);
            if (i <= 1)
                cinemaData.setType(2);
            else
                cinemaData.setType(3);
            tCinemaDataMapper.addOneMessage(cinemaData);
        }
        tCinemaMapper.addRegisterLegalMessage(cinema);
        return Result.success(urls);
    }

    /**
     * 影院注册，从redis中获取id
     *
     * @return
     */
    private int getCinemaIdfromRedis() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String ip = getIpAddr(request);
        ip = ip.replaceAll("\\.", "");

        String key = "CRU." + ip;
        BoundValueOperations<String, String> rs = redisTemplate.boundValueOps(key);
        String value = rs.get();

        int id = 0;
        if (null == value)
            return 0;

        id = Integer.parseInt(value.split("-")[0]);
        return id;
    }

    @Override
    public Result cinemaApplyUpdateCinemaFile(MultipartFile[] files, String addr, double longitude, double latitude, String service) {
        if (null == files || null == addr || null == service)
            return Result.fail(426, "信息不能为空");

        int id = getCinemaIdfromRedis();
        if (id == 0)
            return Result.fail(426, "信息已失效，请重新操作");

        if (tCinemaMapper.selectById(id).getState() != -8)
            return Result.fail(426, "影院信息已上传，请勿重复操作");

        TCinema cinema = new TCinema();
        cinema.setId(id);
        cinema.setAddress(addr);
        cinema.setLongitude(longitude);
        cinema.setLatitude(latitude);
        cinema.setService(service);
        cinema.setState(-7);

        Result re1 = new UpdateUtil().updateFiles("cinema", files, id);
        if (!re1.isSuccess())
            return re1;
        String[] urls = (String[]) re1.getData();
        TCinemaData cinemaData = new TCinemaData();
        cinemaData.setId(99);
        for (int i = 0; i < urls.length; i++) {
            cinemaData.setCinemaId(id);
            cinemaData.setFilePath(urls[i]);
            if (i == 0)
                cinemaData.setType(0);
            else
                cinemaData.setType(1);
            tCinemaDataMapper.addOneMessage(cinemaData);
        }
        tCinemaMapper.addRegisterCinemaMessage(cinema);

        return Result.success(urls);
    }

    @Override
    public Result cinemaApplyGetDefaultContract() {

        int id = getCinemaIdfromRedis();
        if (id == 0)
            return Result.fail(426, "信息已失效，请重新操作");

        TCinema cinema = tCinemaMapper.selectById(id);

        if (tCinemaMapper.selectById(id).getState() != -7)
            return Result.fail(426, "步骤不正确，请勿重复操作");

        //TODO 下载word
        //TODO 解析word
        Map<String, Object> map = new HashMap();

        map.put("甲方", "微票视界");
        map.put("乙方", cinema.getLegalPerson());

        String url = "http://81.69.245.134/sundry/default-contract.jpg";

        TCinemaContract cinemaContract1 = tCinemaContractMapper.findContractByCinemaId(id);
        if (null == cinemaContract1) {

            //复制默认合同到cinema的文件夹 -- 上传合同文件
            Result re1 = downloadFileFunction(url);
            InputStream inputStream = null;
            if (re1.isSuccess()) {
                inputStream = (InputStream) re1.getData();
                Result re2 = new UpdateUtil().updateOneInputStream("cinema", inputStream, id, "contract.jpg");
                if (re2.isSuccess()) {
                    url = (String) re2.getData();
                    TCinemaData cinemaData = new TCinemaData();
                    cinemaData.setId(0);
                    cinemaData.setCinemaId(id);
                    cinemaData.setFilePath(url);
                    cinemaData.setType(4);
                    tCinemaDataMapper.addOneMessage(cinemaData);
                    log.info("默认合同复制成功：{}", url);
                }
            }

            //添加合同
            TCinemaContract cinemaContract = new TCinemaContract();
            cinemaContract.setId(0);
            cinemaContract.setCinemaId(id);
            String num = (int) (Math.random() * 1000000) + "";
            cinemaContract.setNumber(num);
            cinemaContract.setVersion("v1.0");
            cinemaContract.setCreateTime(LocalDateTime.now());
            cinemaContract.setState(0);
            cinemaContract.setPath(url);

            //添加新合同 state=0 count=0
            tCinemaContractMapper.registerAddNewContract(cinemaContract);

            //修改t_cinema中的年费、手续费
            tCinemaMapper.changeAnnualCostAndTipRoot(id, 200000.0, 0.05);

            //修改t_cinema的状态改为-7
            tCinemaMapper.changeContractSetState(id, -7);

            map.put("消息", "第一次拉取，默认合同，生成新合同");
            map.put("url", url);
            map.put("年费", "200000");
            map.put("平台手续费用", "0.05");

        } else {
            map.put("消息", "拉取旧合同");
            map.put("url", cinemaContract1.getPath());
            map.put("年费", cinema.getAnnualCost());
            map.put("平台手续费用", cinema.getTipRoot());
        }

        return Result.success(map);
    }

    @Override
    public Result cinemaApplyChangeContract(double annualCost, double tipRoot) {
        //TODO 获取默认合同的流
        //TODO 修改流的内容
        //TODO 改名并存入
        int id = getCinemaIdfromRedis();
        if (id == 0)
            return Result.fail(426, "信息已失效，请重新操作");

        TCinema cinema = tCinemaMapper.selectById(id);

        if (tCinemaMapper.selectById(id).getState() != -7)
            return Result.fail(426, "步骤不正确，请勿重复操作");

        Map<String, Object> map = new HashMap();

        TCinemaContract contract = tCinemaContractMapper.findContractByCinemaId(id);

        map.put("url", contract.getPath());
        map.put("甲方", "微票视界");
        map.put("乙方", cinema.getLegalPerson());
        map.put("年费", annualCost);
        map.put("平台手续费用", tipRoot);
        map.put("信息", "提交修改信息成功，请等待审核");

        tCinemaMapper.changeAnnualCostAndTipRoot(id, annualCost + 0.0, tipRoot);

        //将t_cinema_contract的state=1 count=count+1 修改时间更新
        tCinemaContractMapper.addContractChangeTimes(id, LocalDateTime.now());

        return Result.success(map);
    }

    @Override
    public Result cinemaApplyConfigContract(MultipartFile signImg) {
        int id = getCinemaIdfromRedis();
        if (id == 0)
            return Result.fail(426, "信息已失效，请重新操作");

        //boss审核合同改变cinema的state=2，导致此处无法连续校验
//        if (tCinemaMapper.selectById(id).getState() != -7)
//            return Result.fail(426, "步骤不正确，请勿重复操作");

        //判断合同的状态：
        TCinemaContract contract = tCinemaContractMapper.findContractByCinemaId(id);
        if (null == contract)
            return Result.fail(426, "请勿跨步骤，发请求");

        Integer state = contract.getState();
        if (state == 1)
            return Result.fail(426, "合同待审核");
        if (state == 2)
            return Result.fail(426, "合同已驳回，请重新申请修改");
//        if (state == 3)
//            return Result.fail(426, "合同已同意，请等待更改状态");
        if (state == 4)
            return Result.fail(426, "合同已作废");
        if (state == 5)
            return Result.fail(426, "合同已签订");

        //让步：
        if (state != 0 && state != 3)
            return Result.fail(426, "非法状态");

        //上传签名文件
        Result re1 = new UpdateUtil().updateOneFile("cinema", signImg, id);
        if (re1.isSuccess()) {
            String url = (String) re1.getData();
            TCinemaData cinemaData = new TCinemaData();
            cinemaData.setId(0);
            cinemaData.setCinemaId(id);
            cinemaData.setFilePath(url);
            cinemaData.setType(5);
            //t_cinema_data数据+1
            tCinemaDataMapper.addOneMessage(cinemaData);
            //t_cinema 修改状态
            tCinemaMapper.changeContractSetState(id, -6);
            //合同表 -- state=5 已签订
            tCinemaContractMapper.changeState(contract.getId(), 5);
            //合同表 -- 添加签名文件path
            tCinemaContractMapper.addSignPathToContract(contract.getId(), url);
            return Result.success(url);
        } else
            return re1;
    }

    @Override
    public Result cinemaApplyUpdateContract(MultipartFile contract, String name, String tel) {
        TCinema cinema = tCinemaMapper.getCinemaByTel(tel);
        int id = cinema.getId();
        Result re1 = new UpdateUtil().updateOneFile("cinema", contract, id);
        if (re1.isSuccess()) {
            String url = (String) re1.getData();
            TCinemaData cinemaData = new TCinemaData();
            cinemaData.setCinemaId(id);
            cinemaData.setFilePath(url);
            cinemaData.setType(4);
            tCinemaDataMapper.addOneMessage(cinemaData);
            return Result.success();
        } else
            return re1;
    }

    @Override
    public Result cinemaApplySendMessage() {
        int id = getCinemaIdfromRedis();
        if (id == 0)
            return Result.fail(426, "信息已失效，请重新操作");

        if (tCinemaMapper.selectById(id).getState() != -6)
            return Result.fail(426, "步骤不正确，请勿重复操作");

        TCinema cinema = tCinemaMapper.selectById(id);
        String tel = cinema.getTel();
        String name1 = cinema.getLegalPerson();
        String name2 = cinema.getCinemaName();
        tCinemaMapper.changeContractSetState(id, 0);
        String message = "恭喜" + name1 + "提交申请成功" + name2 + "影城正在审核请耐心等待";

        //注册成功  删除redis
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String ip = getIpAddr(request);
        ip = ip.replaceAll("\\.", "");
        String key = "CRU." + ip;
        redisTemplate.delete(key);

        return movieTicket.sendMessage(tel, message);
    }

    @Override
    public Result recognizeImg(MultipartFile file) {
        String path = "D:/" + file.getOriginalFilename();
        log.info("身份证路径为：{}", path);
        File f1 = new File(path);
        try {
            file.transferTo(f1);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("创建新文件失败：{}", e.getMessage());
            return Result.fail(426, e.getMessage());
        }
        String message = Idcard.idcard(path);

        IDJsonBean idCard = JSON.parseObject(message, IDJsonBean.class);

        Map<String, String> map = new HashMap();

        map.put("name", idCard.getWords_result().getName().getWords());
        map.put("sex", idCard.getWords_result().getSex().getWords());
        map.put("address", idCard.getWords_result().getAddress().getWords());
        map.put("idNum", idCard.getWords_result().getIdCardNum().getWords());
        map.put("bir", idCard.getWords_result().getBirth().getWords());
        map.put("nation", idCard.getWords_result().getNation().getWords());
        map.put("path", path);

        log.info("身份信息：{}", map.toString());

        return Result.success(map);
    }

    @Override
    public Result updateOneFileFunction(String father, MultipartFile file, int id) {
        return new UpdateUtil().updateOneFile(father, file, id);
    }

    @Override
    public Result updateFilesFunction(String father, MultipartFile[] files, int id) {
        return new UpdateUtil().updateFiles(father, files, id);
    }

    @Override
    public Result downloadFileFunction(String url) {
        return new UpdateUtil().downloadFile(url);
    }

}
